import { getUrl } from './ajax';

export function init ({
  gridSelector = '',
  pagerSelector = '',
  url = '',
  caption = '',
  colNames = [],
  colModel = []
}) {
  const $grid = $(gridSelector);
  const $pageContent = $('.page-content');
  const targetUrl = getUrl(url);
  const options = jqSetting(gridSelector, pagerSelector, targetUrl);
  options.url = targetUrl;
  options.caption = caption;
  options.colNames = colNames;
  options.colModel = colModel.map((item, idx) => {
    item.display = item.display || '';
    item.name = item.name || '';
    item.index = item.index || item.name || '';
    item.width = 'width' in item ? item.width : 90;
    item.editable = item.editable || false;
    item.sortable = item.sortable || false;
    item.sorttype = item.sorttype || '';
    item.hidden = item.hidden || false;
    item.resize = 'resize' in item ? item.resize : true;
    item.fixed = item.fixed || false;
    item.formatter = item.formatter || function (cellValue, options, rowObject) { return cellValue; };
    return item;
  });
  $grid.jqGrid(options);

  $(window).on('resize.jqGrid', function () {
    $grid.jqGrid('setGridWidth', $pageContent.width());
  });

  $(document).on('settings.ace.jqGrid', (ev, eventName, collapsed) => {
    if (eventName === 'sidebar_collapsed' || eventName === 'main_container_fixed') {
      setTimeout(() => {
        $grid.jqGrid('setGridWidth', $grid.closest('[class*="col-"]').width());
      }, 0);
    }
  });

  $(window).triggerHandler('resize.jqGrid');

  $(document).one('ajaxloadstart.page', (e) => {
    $grid.jqGrid('GridUnload');
    const $jqDialog = $('.ui-jqdialog');
    $jqDialog.length > 0 && $jqDialog.remove();
  });
}
